package com.itlong.cloud.controller.engineer;

import com.itlong.cloud.POJO.PO.UserLoginLogPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.engineer.AppEngineerUserInfoVO;
import com.itlong.cloud.POJO.VO.app.engineer.AppEngineerUserOwnProjectVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.controller.current.AppMineController;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.noncore.commons.IUserLoginLogServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppEngineerServiceClient;
import com.itlong.cloud.user.app.IAppMineServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      工程版APP登录控制器。
 * <desc/>
 *
 * @createDate 2017/11/6.
 */
@RestController
@RequestMapping("/engineer")
@RefreshScope
public class AppEngineerLoginController {

    private static final Logger LOG = LoggerFactory.getLogger(AppMineController.class);

    @Autowired
    IAppEngineerServiceClient iAppEgineerServiceClient;

    @Autowired
    IAppMineServiceClient iAppMineServiceClient;

    @Autowired
    private RedisService<AppEngineerUserInfoVO> redisService;

    @Autowired
    IUserLoginLogServiceClient iUserLoginLogServiceClient;

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;

    @Value("${" + PlatformConstants.APP_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String APP_REQUEST_PARAMS_ENCRYPT_KEY;

    /**
     * <desc>
     *     工程版APP端用户登录
     * </desc>
     *
     * @param phoneNo  手机号
     * @param pswd  密码
     * @param sign  密码
     * @return
     * @author shengen.T
     * @createDate 2017/11/6
     */
    @RequestMapping(path = "/login",method = RequestMethod.POST)
    @ResponseBody
    public  MessageVO engineerAppUserLogin(String phoneNo,String pswd,String createTime,String sign,HttpServletRequest request){
        MessageVO messageVO;
        try {
            //判断登录账号
            if(StringUtils.isBlank(phoneNo)){
                return new MessageVO(AppErrorCodeEnum.PHONE_NO_EMPTY_ERR.getErrorCode());
            }
            //判断密码
            if(StringUtils.isBlank(pswd)){
                return new MessageVO(AppErrorCodeEnum.PASSWORD_EMPTY_ERR.getErrorCode());
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNo",phoneNo);
            params.put("pswd",pswd);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            DateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
            Date nowTime = new Date();
            UserLoginLogPO userLoginLogPO = new UserLoginLogPO(phoneNo,null, HttpProtocolUtil.getIpAddr(request));
            userLoginLogPO.setSystemType(3);
            AppEngineerUserInfoVO userInfoPO = iAppEgineerServiceClient.getEngineerAppUserLogin(phoneNo);
            if(userInfoPO==null){
                return new MessageVO(AppErrorCodeEnum.ACCOUNT_NOT_EXIST_ERR.getErrorCode());
            }
//            暂时注掉
//            if (userInfoPO.getAuthType() == 1 &&
//                    (nowTime.before(dateFormat.parse(userInfoPO.getAuthStartTime())) || nowTime.after(dateFormat.parse(userInfoPO.getAuthEndTime())))){
//                return new MessageVO(AppErrorCodeEnum.ACCOUNT_PASS_TIME_ERROR.getErrorCode());
//            }
            if(!userInfoPO.getPassword().equals(Md5EncryptUtil.md5(pswd))){
                return new MessageVO( AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode());
            }
            if(StringUtils.isNotEmpty(userInfoPO.getUserId())){
                Integer resCount = iAppEgineerServiceClient.checkEngineerLogin(userInfoPO.getUserId());
                if(resCount<1){
                    return new MessageVO(AppErrorCodeEnum.NO_ENGINEER_AUTH.getErrorCode());
                }
            }
            AppEngineerUserInfoVO newUserInfoVO = iAppEgineerServiceClient.logEngineerLoginInfo(userInfoPO);
            if(newUserInfoVO==null){
                LOG.info("工程APP登录信息缓存插入失败，登录账号:"+phoneNo);
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }else {
                StringHandlerUtil.formatString(newUserInfoVO);
                if(newUserInfoVO.getProjects()==null){
                    newUserInfoVO.setProjects(new ArrayList<>());
                }
                for (AppEngineerUserOwnProjectVO vo:newUserInfoVO.getProjects()){
                    StringHandlerUtil.formatString(vo);
                }
            }
            userLoginLogPO.setRealName(newUserInfoVO.getUserName());
            userLoginLogPO.setDescription("登录" + BaseErrorCodeEnum.SUCCESS.getErrorCode().getCodeMsg());
            iUserLoginLogServiceClient.save(userLoginLogPO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),newUserInfoVO);
        }catch (Exception e){
            throw new DataAccessException("【工程版APP登录】登录失败",e);
        }
        return messageVO;
    }


    /**
     * <desc>
     *     工程版APP端_我的，退出登录
     * </desc>
     * @param token
     * @return
     * @createDate 2017/10/10
     * @author shengen.T
     */
    @LoggerInfo(operateDesc = LogDescConstant.LOGIN_OUT)
    @RequestMapping(path = "/loginOut",method = RequestMethod.POST)
    @ResponseBody
    public MessageVO loginOut(String token,HttpServletRequest request){
        try {
            if (StringUtils.isBlank(token)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String userId = UserTokenUtil.tokenDecrypt(token,APP_USER_TOKEN_KEY);
            boolean flag=false;
            // boolean flag = redisService.del(RedisConstant.APP_LOGIN+userId);
            AppEngineerUserInfoVO appUserCacheVO = redisService.getObject(RedisConstant.APP_LOGIN+userId,AppEngineerUserInfoVO.class);
            UserLoginLogPO userLoginLogPO=null;
            if (appUserCacheVO != null) {
               userLoginLogPO = new UserLoginLogPO(appUserCacheVO.getPhoneNo(),appUserCacheVO.getUserName(), HttpProtocolUtil.getIpAddr(request));
                userLoginLogPO.setSystemType(3);
                flag = redisService.set(RedisConstant.APP_LOGIN + userId, RedisConstant.LOGIN_OUT_APP_USER_TOKEN_TIME, appUserCacheVO);
            }
            if (flag){
                //LOG.info("【工程版APP端_我的版块】登出清理缓存成功");
                if(userLoginLogPO!=null){
                    userLoginLogPO.setDescription("退出"+BaseErrorCodeEnum.SUCCESS.getErrorCode().getCodeMsg());
                    iUserLoginLogServiceClient.save(userLoginLogPO);
                }
                return  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }else {
                LOG.info("【工程版APP端_我的版块】登出清理缓存失败");
                if(userLoginLogPO!=null){
                    userLoginLogPO.setDescription("退出"+BaseErrorCodeEnum.ERROR.getErrorCode().getCodeMsg());
                    iUserLoginLogServiceClient.save(userLoginLogPO);
                }
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
        }catch (Exception e){
            throw new DataAccessException("【工程版APP端_我的_退出登录】退出登录失败",e);
        }
    }
}
